
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

import pandas as pd
import numpy as np
import pickle
import logging

from src.models.deep_hybrid_model import DeepHybridModel
from src.training.hybrid_trainer import HybridTrainer

# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # 降低TensorFlow日志级别

def verify_evaluation_logic():
    """
    该脚本用于验证评估逻辑是否正确，跳过耗时的训练步骤。
    """
    print("🚀 开始验证评估逻辑...")
    
    try:
        # 1. 加载预处理的数据
        print("📥 加载预处理数据...")
        processed_dir = "data/processed/"
        
        user_features = pd.read_pickle(f"{processed_dir}/user_features.pkl")
        movie_features = pd.read_pickle(f"{processed_dir}/movie_features.pkl")
        
        with open(f"{processed_dir}/user_id_map.pkl", 'rb') as f:
            user_id_map = pickle.load(f)
        with open(f"{processed_dir}/movie_id_map.pkl", 'rb') as f:
            movie_id_map = pickle.load(f)
            
        interactions = pd.read_pickle(f"{processed_dir}/interaction_features.pkl")
        
        print("📊 数据加载完成。")

        # 2. 准备数据，获取验证集
        model_config = {
            'embedding_dim': 64,
            'hidden_layers': [512, 256, 128],
            'dropout_rates': [0.3, 0.3, 0.2],
            'learning_rate': 0.001,
            'batch_size': 2048,
            'epochs': 1,  # 仅用于配置，不实际训练
            'use_attention': True,
            'use_batch_norm': True,
            'l2_reg': 0.0001
        }
        print("📋 准备训练和验证数据...")
        trainer = HybridTrainer(None, config=model_config)
        
        # 使用 prepare_training_data 获取处理后的数据
        _, val_data, processed_movie_features = trainer.prepare_training_data(
            ratings_df=interactions,
            user_features=user_features,
            movie_features=movie_features,
            user_id_map=user_id_map,
            movie_id_map=movie_id_map,
            test_size=0.2,
            sample_ratio=0.1  # 使用少量数据以加快速度
        )

        # 3. 构建一个未训练的模型
        print("🧠 构建一个模拟（未训练的）模型...")
        n_users = len(user_id_map)
        n_movies = len(movie_id_map)
        user_feature_dim = user_features.shape[1]
        # 使用处理后的 movie_features 维度
        movie_feature_dim = processed_movie_features.shape[1]

        model_builder = DeepHybridModel(
            n_users=n_users,
            n_movies=n_movies,
            user_feature_dim=user_feature_dim,
            movie_feature_dim=movie_feature_dim,
            config=model_config
        )
        model = model_builder.build_model()
        trainer.model = model
        print("模型构建完成。")

        # 4. 直接执行评估
        print("📈 使用未训练的模型执行评估...")
        if val_data is not None:
            metrics = trainer.evaluate(val_data)
            print(f"📊 评估完成，指标（无意义，仅用于验证流程）: {metrics}")
        else:
            print("⚠️ 未生成验证数据，无法执行评估。")

        print("✅ 验证脚本执行成功！这表明数据解包和评估流程已修复。")

    except Exception as e:
        logging.error(f"验证过程中出错: {e}", exc_info=True)
        print("❌ 验证脚本执行失败。")
        raise

if __name__ == "__main__":
    verify_evaluation_logic()
